<template>
  <div>

    <div v-if="center">
      <h1>地址: {{ address }}</h1>
    </div>

    <el-amap
        ref="map"
        map-style="amap://styles/62009be025f187dd3eafe327d2e55b8e"
        :center="center"
        :zoom="zoom"
        view-mode="3D"
        @init="initMap"
        @click="clickMap"
        @zoomend="zoomchange"
        class="amap-demo"
    >
      <!-- 比例尺 -->
      <el-amap-control-scale :visible="visible"></el-amap-control-scale>
      <!-- 缩放 -->
      <el-amap-control-tool-bar :visible="visible" position="RB" :offset="[30, 200]"></el-amap-control-tool-bar>
      <!-- 旋转 -->
      <el-amap-control-control-bar :visible="visible" position="LT" :offset="[20, 80]"></el-amap-control-control-bar>
      <!-- 地图类型切换 -->
      <el-amap-control-map-type :visible="visible" ></el-amap-control-map-type>
      <!-- 鹰眼切换 -->
      <el-amap-control-hawk-eye :visible="visible"></el-amap-control-hawk-eye>
      <!-- POI搜索 -->
      <el-amap-search-box :visible="visible" @select="selectPoi" @choose="choosePoi" ></el-amap-search-box>
      <!-- 地图标点 -->
      <el-amap-marker v-for="(marker, index) in markers" :key="index" :position="marker.position"></el-amap-marker>
      <!-- 定位 -->
      <el-amap-control-geolocation :visible="visible" position="RB" :offset="[180, 20]"></el-amap-control-geolocation>
    </el-amap>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 逆地理编码解析实例
      geocoder: null,
      visible: true,
      // 搜索关键字
      key: '',
      center: [114.36244010925293, 30.53557691256986],
      address: '',
      zoom: 12,
      markers: [],
      // markers: [
      //   {
      //     position: [121.5273285, 31.21515044],
      //     id: 1
      //   }
      // ],
    };
  },
  methods: {
    // 搜索
    search () {
      alert(this.key);
    },
    // 鼠标点击或者回车选中某个POI信息时触发此事件
    selectPoi (e) {
      const poi = e.poi;
      this.addPointer([poi.location.lng, poi.location.lat]);
    },
    // 鼠标或者键盘上下键选择POI信息时触发此事件
    choosePoi (e) {
      const poi = e.poi;
      this.addPointer([poi.location.lng, poi.location.lat]);
    },
    // 地图初始化完成
    initMap (e) {
      // e 是地图实例
      const geocoder = new window.AMap.Geocoder();
      this.geocoder = geocoder;
    },
    // 地图点击事件
    clickMap (e) {
      this.addPointer([e.lnglat.lng, e.lnglat.lat]);
    },
    // 地图缩放
    zoomchange (e) {
      this.zoom = e.target.getZoom();
    },
    // 增加标点
    addPointer (position) {
      // 改变中心位置
      this.center = position;
      // 添加标点
      this.markers = [{
        position,
        id: Math.ceil(Math.random() * 1000),
      }]
      // 放大
      this.zoom = 18;
      this.geocoder.getAddress(position, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result为对应的地理位置详细信息
          this.address = result.regeocode.formattedAddress;
        }
      })
    },
  },
}
</script>

<style scoped>
.amap-demo {
  height: 700px;
}
</style>
